using AhpilyServer;
using AhpilyServers;
using GameServer.Cache.Fight;
using Protocol.Constant;
using Protocol.Dto.Fight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GameServer.Cache.Match
{
    /// <summary>
    /// 匹配房间
    /// </summary>
    public class MatchRoom
    {
        /// <summary>
        /// 唯一标识
        /// </summary>
        public int Id { get; private set; }
        /// <summary>
        ///  用户Id列表
        /// </summary>
        public Dictionary<int, ClientPeer> UIdClientDict { get; private set; }

        /// <summary>
        ///  已准备的用户Id列表
        /// </summary>
        public List<int> ReadyUIdList { get; private set; }


        public MatchRoom(int id)
        {
            this.Id = id;
            this.ReadyUIdList = new List<int>();
            this.UIdClientDict = new Dictionary<int, ClientPeer>();
        }



        /// <summary>
        /// 判断房间是否已满
        /// </summary>
        public bool IsFull()
        {
            return UIdClientDict.Count == 3;
        }

        /// <summary>
        /// 判断房间是否空了
        /// </summary>
        public bool IsEmpty()
        {
            return UIdClientDict.Count == 0;
        }

        /// <summary>
        /// 判断房间用户是否都准备了
        /// </summary>
        public bool IsAllReady()
        {
            return ReadyUIdList.Count == 3;
        }

        /// <summary>
        /// 进入房间
        /// </summary>
        public void Enter(int userId, ClientPeer client)
        {
            UIdClientDict.Add(userId, client);
        }

        /// <summary>
        /// 离开房间
        /// </summary>
        public void Leave(int userId)
        {
            UIdClientDict.Remove(userId);
        }

        /// <summary>
        /// 玩家准备
        /// </summary>
        public void Ready(int userId)
        {
            ReadyUIdList.Add(userId);
        }

        public List<int> GetIdList()
        {
            return UIdClientDict.Keys.ToList();
        }
        /// <summary>
        /// 广播房间内的所有玩家信息
        /// </summary>
        public void Brocast(int opCode, int subCode, object value, ClientPeer curClient = null)
        {
            SocketMsg msg = new SocketMsg(opCode, subCode, value);
            byte[] data = EncodeTools.EncodeMsg(msg);
            byte[] packet = EncodeTools.EncodePacket(data);
            foreach (var client in UIdClientDict.Values)
            {
                if (client == curClient)
                    continue;
                client.Send(packet);
            }
        }
    }
}
